package com.excelliance.open;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.excelliance.lbsdk.base.BaseUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class SwitchView extends FrameLayout {
    private List<ImageView> imageViews = new ArrayList<ImageView>();
    private List<Animation> outAnim;//淡出动画
    private List<Animation> inAnim;//淡入动画
    private Context mContext;
    private Handler handler = new Handler(Looper.getMainLooper());
    private int count = 0;
    private long time=5000;//图片显示的时长
    private long aniTime=1500;//淡入淡出显示的时长
    private long noAniTime=0;
    private int screenWidth = 0;
    private int screenHeight = 0;
    private boolean flag = false;

    public static final String TAG = "SwitchView";

    public SwitchView(Context context) {
        this(context, null);
    }

    public SwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;

        //获取手机屏幕的匡高
        WindowManager wm = (WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getRealMetrics(displayMetrics);
            screenWidth = displayMetrics.widthPixels;
            screenHeight = displayMetrics.heightPixels;
        } else {
            screenWidth = wm.getDefaultDisplay().getWidth();
            screenHeight = wm.getDefaultDisplay().getHeight();
        }

        if (BaseUtil.isLandscape(context, NextChapter.class.getName())) {
            if (screenHeight > screenWidth) {
                screenWidth = screenWidth + screenHeight;
                screenHeight = screenWidth - screenHeight;
                screenWidth = screenWidth - screenHeight;
            }
        }

        try{
            //获取图片列表并设置
            int i = 0;
            while(true){
                Bitmap b = getNewVersionBg(i);
                if(b == null){
                    break;
                }
                imageViews.add(getImageView(picture(b,0)));
                i++;
            }
            if(imageViews.size() == 0){
                int v = context.getResources().getIdentifier("lebian_main_background_normal", "drawable", context.getPackageName());
                if (v > 0){
                    imageViews.add(getImageView(picture(null,v)));
                }
                int j = 0;
                while (true) {
                    v = context.getResources().getIdentifier("lebian_main_background_normal_"+(j+1), "drawable", context.getPackageName());
                    if (v > 0){
                        imageViews.add(getImageView(picture(null,v)));
                    } else{
                        break;
                    }
                    j++;
                }
            }
            setImageViews(imageViews,null);
        }catch (Throwable throwable){
            Log.e(TAG,throwable.getMessage());
            imageViews = null ;
            ImageView iv = new ImageView(context);
            int v = context.getResources().getIdentifier("lebian_main_background_normal", "drawable", context.getPackageName());
            iv.setImageResource(v);
            setImageViews(null,iv);
        }
    }

    //设置需要轮播的图片
    public void setImageViews(List<ImageView> imageViews, View view) {
        LayoutParams layoutParams = new LayoutParams(screenWidth, screenHeight);
        if(imageViews != null ){
            this.imageViews = imageViews;
            for (int i = 0; i < imageViews.size(); i++) {
                addView(imageViews.get(i),layoutParams);
            }
            if(imageViews.size() > 1){
                createAnim();
                startAnim();
            }
        }else {
            addView(view,layoutParams);
        }
    }

    //创建动画
    private void createAnim() {
        outAnim = new ArrayList<Animation>();
        inAnim = new ArrayList<Animation>();
        for (int i = 0; i < imageViews.size(); i++) {
            Animation outAwayAnim = createOutAwayAnim();
            outAwayAnim.setFillAfter(true);
            outAnim.add(outAwayAnim);
            Animation outNearAnim = createOutNearAnim();
            outNearAnim.setFillAfter(true);
            inAnim.add(outNearAnim);
        }
    }

    //开启渐入渐出的动画
    private void startAnim() {
        final int size = imageViews.size();
        handler.post(new Runnable() {
            @Override
            public void run() {
                final int i = count % size;
                if(!flag){//第一张图片不需要淡出的动画，且持续时间之后才淡入
                    Animation anim = new AlphaAnimation(0f, 1f);
                    anim.setDuration(noAniTime);
                    anim.setFillAfter(true);
                    ImageView imageView = imageViews.get(size - 1 - i);
                    imageView.startAnimation(anim);
                } else if (count < size) {
                    if (i == size - 1) {
                        ImageView imageView = imageViews.get(0);
                        imageView.startAnimation(outAnim.get(0));
                        ImageView imageView2 = imageViews.get(size - 1);
                        imageView2.startAnimation(inAnim.get(size - 1));
                    } else {
                        //当前的淡出,下一张淡入
                        ImageView imageView = imageViews.get(size - 1 - i);
                        imageView.startAnimation(outAnim.get(size - 1 - i));
                    }
                } else {
                    if (i == size - 1) {
                        //当显示到最后一张的时候,要跳到第一张
                        ImageView imageView = imageViews.get(0);
                        imageView.startAnimation(outAnim.get(0));
                        ImageView imageView2 = imageViews.get(size - 1);
                        imageView2.startAnimation(inAnim.get(size - 1));
                    } else {
                        //当前的淡出,下一张淡入
                        ImageView imageView = imageViews.get(size - 1 - i);
                        imageView.startAnimation(outAnim.get(size - 1 - i));
                        ImageView imageView2 = imageViews.get(size - 2 - i);
                        imageView2.startAnimation(inAnim.get(size - 2 - i));
                    }
                }
                if(flag){
                    count++;
                }else{
                    count = 0;
                    flag = true;
                }
                handler.postDelayed(this, time);
            }
        });
    }

    //创建一个淡出的动画
    public  Animation createOutAwayAnim() {
        AnimationSet ret = new AnimationSet(false);
        Animation anim = new AlphaAnimation(1f, 0f);//淡出动画
        if(GlobalSettings.USE_ANIMAL_WHEN_SWITCH_VIEW){
            anim.setDuration(aniTime);
        }else{
            anim.setDuration(noAniTime);
        }
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        ret.addAnimation(anim);
        return ret;
    }

    //创建一个淡入的动画
    public  Animation createOutNearAnim() {
        AnimationSet ret = new AnimationSet(false);
        Animation anim = new AlphaAnimation(0f, 1f);//淡入动画
        if(GlobalSettings.USE_ANIMAL_WHEN_SWITCH_VIEW){
            anim.setDuration(aniTime);
        }else{
            anim.setDuration(noAniTime);
        }
        anim.setInterpolator(new AccelerateDecelerateInterpolator ());
        ret.addAnimation(anim);
        return ret;
    }

    //得到ImageView数组
    private ImageView getImageView(Bitmap bitmap){
        ImageView imageView = new ImageView(mContext);
        imageView.setImageBitmap(bitmap);
        return imageView;
    }

    //将图片转化为适应屏幕的Bitmap类型
    public Bitmap picture(Bitmap bitmap, int index){
        if(bitmap == null){
            bitmap = BitmapFactory.decodeResource(mContext.getResources(), index);
        }
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        float scaleWidth = ((float) screenWidth) / width;
        float scaleHeight = ((float) screenHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        float rad = Math.max(scaleWidth,scaleHeight);
        int xStart = 0;
        int yStart = 0;
        if(GlobalSettings.SCALE_MODE_IN_NEXTCHAPTER == 0){
            matrix.postScale(rad, rad);
            if(rad == scaleHeight){
                xStart = (int)((width-screenWidth/rad)/2);
                width = (int)(screenWidth/rad);
            }else{
                yStart = (int)((height-screenHeight/rad)/2);
                height = (int)(screenHeight/rad);
            }
        }else if(GlobalSettings.SCALE_MODE_IN_NEXTCHAPTER == 1){
            matrix.postScale(rad, rad);
        }else {
            matrix.postScale(scaleWidth, scaleHeight);
        }
        Log.d(TAG,"scaleMode is " + GlobalSettings.SCALE_MODE_IN_NEXTCHAPTER + ",rad is " + rad + ",xStart is " + xStart + ",yStart is "+ yStart);
        // 得到新的图片
        bitmap = Bitmap.createBitmap(bitmap, xStart, yStart, width, height, matrix, true);
        return bitmap;
    }

    private Bitmap getNewVersionBg(int index) {
        String path = Environment.getExternalStorageDirectory().toString() + "/Android/data/" + mContext.getPackageName() + "/files/lebian/";
        String path2 = mContext.getApplicationInfo().dataDir + "/lebian/";
        Bitmap bitmap;
        if (new File(path + "lebian_main_background_normal_" + index + ".jpg").exists()) {
            bitmap = BitmapFactory.decodeFile(path + "lebian_main_background_normal_" + index + ".jpg");
        } else if (new File(path2 + "lebian_main_background_normal_" + index + ".jpg").exists()) {
            bitmap = BitmapFactory.decodeFile(path2 + "lebian_main_background_normal_" + index + ".jpg");
        } else {
            return null;
        }
        return bitmap;
    }
}